package insight.google.game.era.core;

import insight.google.game.era.bo.GameUser;
import insight.google.game.era.core.cache.AppCacheManager;
import insight.google.game.era.data.GameUserDataManager;
import insight.google.game.era.data.TransactionHandler;
import insight.google.game.era.data.User;
import insight.google.game.era.data.UserDataManager;

import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpSession;

import net.sf.jsr107cache.Cache;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.ScriptProxy;

public class UserSessionManager {

	private static UserSessionManager instance;
	
//	private Cache cache;
	
	public static final String ATTR_USER = "user";
	
	private UserDataManager userDataManager;
	private TransactionHandler txHandler;
	private UserSessionManager(TransactionHandler txHandler){
		this.txHandler = txHandler;
		
//		cache  = AppCacheManager.getInstance().getCache();
	}
	
	public static UserSessionManager getInstance(TransactionHandler txHandler){
		return new UserSessionManager(txHandler);
	}
	
	public User getUserBySession(){
		//userDataManager = new UserDataManager(this.txHandler);
		userDataManager = new UserDataManager();
		return this.getUser();
		
	}
	
	
	private User getUser(){
		User currUser = null;
		Object sessionAttr = this.getSessionAttributeByName(ATTR_USER);
		if(sessionAttr != null){
			currUser = userDataManager.findByName((String)sessionAttr);
		}
		
		if (currUser != null) {
			currUser.setScriptProxy(new ScriptProxy(getUserScriptSession(currUser.getName())));
		
		}
		return currUser;
	}
	
	
	public User getUserBySession(boolean isDetachable){
		userDataManager = new UserDataManager(this.txHandler,isDetachable);
		return this.getUser();
	}
	
	
	public Object getSessionAttributeByName(String attrName){
		return this.getSessionFromWebContext().getAttribute(attrName);
	}
	
	public HttpSession getSessionFromWebContext(){
		return WebContextFactory.get().getSession();
	}
	
	public ScriptProxy getNewScripProxy(String user){
		return new ScriptProxy(this.getUserScriptSession(user));
	}
	
	public ScriptSession getUserScriptSession(String user) {
		this.getSessionFromWebContext().setAttribute(ATTR_USER, user);
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute(ATTR_USER, user);
		return scriptSession;
	}
	
}
